package com.example.springtaskschedule.service.impl;

import com.example.springtaskschedule.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * TestServiceImple
 *
 * @author zhouxianfeng
 * @date 2021-4-25
 */
@Component
@Slf4j
public class TestServiceImple implements TestService {

    @Override
    @Async
    public void testAsync() throws Exception {
        log.info("异步执行开始");
        Thread.sleep(10 * 1000);
        if (1 == 1) {
            throw new Exception("test");
        }
        log.info("异步执行结束");

    }

    @Override
    @Async("test1TaskExecutor")
    public Future<String> test() throws Exception {
        log.info("异步执行开始");
        Thread.sleep(10 * 1000);
        if (1 == 1) {
            throw new Exception("test");
        }
        log.info("异步执行结束");
        return new AsyncResult<String>("success");
    }

    @Override
    //如果指定错误的线程池名字会直接报错
    @Async("test")
    public Future<String> test1() throws Exception {
        log.info("异步执行开始");

        log.info("异步执行结束");
        return new AsyncResult<String>("success");
    }

    @Override
    @Scheduled(cron = "0/10 * * * * *")
    public void testSchedule() {
        log.info("执行 schedule");
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("异步执行结束");
    }


}
